package sk.stuba.fiit.arthur.web.mvc.model.service;

import java.util.Collection;
import java.util.LinkedList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;

import sk.stuba.fiit.arthur.web.mvc.model.dao.DocumentDao;
import sk.stuba.fiit.arthur.web.mvc.model.entity.DocumentEntity;
import sk.stuba.fiit.arthur.ws.client.DocumentServiceClient;
import sk.stuba.fiit.pki.ws.schema.beans.Document;
import sk.stuba.fiit.pki.ws.schema.beans.DocumentResponse;
import sk.stuba.fiit.pki.ws.schema.beans.GetDocumentRequest;

@Service("DocumentService")
public class DocumentServiceImpl implements DocumentService {

	@Autowired()
	private DocumentDao documentDao;
	
	@Autowired()
	private DocumentServiceClient documentServiceClient;
	
	public Collection<DocumentEntity> findDocuments() throws DataAccessException{
		return documentDao.findDocuments();
	}

	public void save(DocumentEntity documentEntity) {
		documentDao.save(documentEntity);
	}

	@Secured ({"ROLE_ADMIN"})
	public void delete(DocumentEntity documentEntity) {
		documentDao.delete(documentEntity);
	}

	public DocumentEntity findDocumentById(Integer id)
			throws DataAccessException {
		return documentDao.findDocumentById(id);
	}

	public Collection<DocumentEntity> getUnsignedDocuments(String name) {
		Collection<DocumentEntity> documentEntityList = new LinkedList<DocumentEntity>();
		DocumentResponse documentResponse = documentServiceClient.getDocuments(new GetDocumentRequest().withName(name));
		if(documentResponse != null && documentResponse.getDocument() != null && documentResponse.getDocument().size()>0){
			for (Document document : documentResponse.getDocument()) {
				DocumentEntity documentEntity = new DocumentEntity();
				documentEntity.setId(document.getId());
				documentEntity.setName(document.getName());
				documentEntity.setDescription(document.getDescription());
				documentEntityList.add(documentEntity);
			}
		}
		return documentEntityList;
	}
}
